import Toast from '@vant/weapp/toast/toast';
import { getStudentInfo, updateStudentInfo } from '../../utils/api-v2';

Page({
  data: {
    userInfo: {
      name: '',
      number: '',
      sex: 1,
      className: '',
      majorName: '',
      departmentName: '',
      email: '',
      birthday: ''
    },
    originalInfo: {}, // 保存原始信息，用于取消编辑
    isEditing: false,
    saving: false,
    sexOptions: [
      { label: '男', value: 1 },
      { label: '女', value: 2 }
    ]
  },

  onLoad() {
    this.loadUserInfo();
  },

  // 加载用户信息
  loadUserInfo() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });

    // 调用接口 GET /student/info
    getStudentInfo()
      .then((res) => {
        Toast.clear();
        const userInfo = res.data || {};
        this.setData({
          userInfo: userInfo,
          originalInfo: JSON.parse(JSON.stringify(userInfo))
        });
      })
      .catch((err) => {
        Toast.clear();
        console.error('加载用户信息失败:', err);
        Toast.fail('加载失败，请稍后重试');
      });
  },

  // 开始编辑
  startEdit() {
    this.setData({
      isEditing: true,
      originalInfo: JSON.parse(JSON.stringify(this.data.userInfo))
    });
  },

  // 取消编辑
  cancelEdit() {
    this.setData({
      isEditing: false,
      userInfo: JSON.parse(JSON.stringify(this.data.originalInfo))
    });
    Toast('已取消编辑');
  },

  // 保存信息
  saveInfo() {
    // 验证邮箱格式
    if (this.data.userInfo.email) {
      const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailReg.test(this.data.userInfo.email)) {
        Toast.fail('请输入正确的邮箱格式');
        return;
      }
    }

    this.setData({ saving: true });

    // 调用接口 PUT /student/info
    const updateData = {
      name: this.data.userInfo.name,
      birthday: this.data.userInfo.birthday,
      className: this.data.userInfo.className,
      departmentName: this.data.userInfo.departmentName,
      email: this.data.userInfo.email,
      majorName: this.data.userInfo.majorName,
      number: this.data.userInfo.number,
      sex: this.data.userInfo.sex
    };

    updateStudentInfo(updateData)
      .then((res) => {
        this.setData({
          saving: false,
          isEditing: false,
          originalInfo: JSON.parse(JSON.stringify(this.data.userInfo))
        });
        Toast.success('保存成功');
      })
      .catch((err) => {
        this.setData({ saving: false });
        Toast.fail(err.msg || '保存失败');
        console.error('保存失败:', err);
      });
  },

  // 输入事件处理
  onNameInput(e) {
    this.setData({
      'userInfo.name': e.detail.value
    });
  },

  onClassNameInput(e) {
    this.setData({
      'userInfo.className': e.detail.value
    });
  },

  onMajorNameInput(e) {
    this.setData({
      'userInfo.majorName': e.detail.value
    });
  },

  onDepartmentNameInput(e) {
    this.setData({
      'userInfo.departmentName': e.detail.value
    });
  },

  onEmailInput(e) {
    this.setData({
      'userInfo.email': e.detail.value
    });
  },

  onSexChange(e) {
    this.setData({
      'userInfo.sex': parseInt(e.detail.value) + 1
    });
  },

  onBirthdayChange(e) {
    this.setData({
      'userInfo.birthday': e.detail.value
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.clearStorageSync();
          
          Toast.success('已退出登录');
          
          // 延迟跳转到登录页
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/login/login'
            });
          }, 1000);
        }
      }
    });
  }
});
